﻿using System;
using System.Threading;
using System.Windows.Navigation;
namespace XamlMvp.Controls
{
    public partial class MvpPage : IViewPage
    {
        public event EventHandler Saving;
        public event EventHandler Canceled;        
        public event EventHandler Deleted;
        public event EventHandler<MvpNavigationEventArgs> NavigatedFrom;
#if WINDOWS_PHONE
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            var context = Binders.Presenters.Context;
            if (!context.WasApplicationInstancePreserved)
            {
                Binders.Presenters.Bind(this, context.State);
            }
        }
#else
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            var context = Binders.Presenters.Context;
            Binders.Presenters.Bind(this, context.State);
        }
#endif
        public bool IsAutoEventWireUp { get { return View.GetAutoEventWireUp(this); } }

        protected virtual void OnSave(object sender, EventArgs e)
        {
            if (Saving != null)
            {
                FocusHack();
                Saving(sender, e);
            }
        }

        protected virtual void OnCancel(object sender, EventArgs e)
        {
            if (Canceled != null)
            {
                Canceled(sender, e);
            }
        }

        protected virtual void OnDeleted(object sender, EventArgs e)
        {
            if (Deleted != null)
            {
                Deleted(sender, e);
            }
        }

        partial void FocusHack();

        IDispatcher dispatcher;
        IDispatcher IView.Dispatcher
        {
            get
            {
                if (dispatcher == null)
                {
                    dispatcher = new DispatcherWrapper(base.Dispatcher);
                }
                return dispatcher;
            }
        }

        INavigationService navigationService;
        INavigationService IViewPage.NavigationService
        {
            get
            {
                if (navigationService == null)
                {
                    Interlocked.Exchange(ref navigationService, new NavigationServiceWrapper(base.NavigationService));
                }
                return navigationService;
            }
        }
        INavigationContext navigationContext;
        INavigationContext IViewPage.NavigationContext
        {
            get
            {
                if(navigationContext == null)
                {
                    Interlocked.Exchange(ref navigationContext, new NavigationContextWrapper(base.NavigationContext));
                }
                return navigationContext;
            }
        }
    }

}